<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<c:set var="ctx" value="${pageContext.request.contextPath}" />
<c:set var="queryList"
	value="${pageContext.request.contextPath}/user/list" />

<link rel="stylesheet" href="${ctx}/static/css/groups.css">
<div class="iframe-cot pull-right" id="smIframe" style="background:#FFFFFF;">
		<div class="right-form">
			<form id="_query_form" action="" class="form-inline" onsubmit="return false;">
				<div class="tb_search">
	            <div class="pull-left">
					<span class="search-more">更多条件<i class="fa fa-angle-down ml5"></i></span>
					<div class="form-group-Wdate" >
						<label for="userName">用户名：</label> 
						<input type="text" name="userName" value="${userName }" />
					</div>
					
					<div class="form-group">
						<label for="userName">登录名：</label> 
						<input type="text" name="loginName" value="${loginName }" />
					</div>
					
					<%-- <div class="form-group">
						<label for="postName">岗位：</label>
					 	<input type="text" id="s_postName" name="postName" value="${postName }" readOnly placeHolder="请选择" />
					 	<input type="hidden" id="s_postId" name="postId" value="${postId }" />
					</div> --%>
					<div class="form-group-Wdate">
						<label for="unitName">机构：</label> 
						<input type="text" id="s_unitName" name="unitName" value="${unitName }" readOnly placeHolder="请选择" />
						<input id="s_unitId" name="unitId" type="hidden" value="${unitId}">	
					</div>
					
					<%-- <div class="form-group">
						<label for="postName">${status} 状态 ：</label>
	                 		<select class="form-control-select" value="${status}" name="status" >
	                       	<option value="" <c:if test="${ empty status }">selected='selected'</c:if>>请选择</option>
	                        	<option value="1" <c:if test="${ '1' eq status }">selected='selected'</c:if>>启用</option>
	                        	<option value="0" <c:if test="${ '0' eq status }">selected='selected'</c:if>>停用</option>
	                    	</select>
	                </div> --%>
				</div>
				</div>
			</form>
		</div>
		
		<div class="line-e6e"></div>
		
	       <div class="form-top">
	         	<div class="pull-left">
	         	<!-- 	<button class="btn btn-default" onclick="goAdd('${ctx}/user/goEdit','新增用户')">
					<i class="fa fa-plus mr5"></i>新增</button> 
				<button class="btn btn-default" onclick="goUpdateUser('${ctx}/user/goEdit?currentPage=${pageBean.currentPage}&pageSize=${pageBean.pageSize }','修改用户信息')">
					<i class="fa fa-pencil mr5"></i>编辑</button>
				-->
				<shiro:hasPermission name="common-service-user:grantRole">
				<button class="btn btn-default" onclick="goUserRoles()">
					<i class="fa fa-pencil mr5"></i>赋角色</button> 
				 </shiro:hasPermission> 
				 <!--
				 <button class="btn btn-default" onclick="enable()"><i class="fa fa-check-circle-o mr5"></i>启用</button>
             	<button class="btn btn-default" onclick="ban()"><i class="fa fa-ban mr5"></i>停用</button>
            	-->
	         	</div>
	         	
	         	<div class="pull-right">
	         	<shiro:hasPermission name="common-service-user:query">
				<a class="btn btn-orange" onclick="changePage('${queryList }/table','#_query_form','1','${pageBean.pageSize }',0,true)">
				<i class="fa fa-search mr5"></i>查询</a>
				<a class="btn btn-blue" onclick="clearCondition()"><i class="fa fa-trash-o mr5"></i>清空</a>
				</shiro:hasPermission>
				</div>
	       </div>
		<div id="table-papination">
			
		</div>
</div>

	<!--main end-->

<!-- 放到index.jsp后面了，这个div的父级必须是body -->
<!-- <div id="treediv" style='overflow:scroll;display:none; position:absolute;width:300px;height:200px;background-color:#eeffdd; border:1px solid #BEC0BF;padding:5px;font-size:12px;'>
	<a onclick="hidetreediv();" href="#" class="link-red mr5" style="cursor:pointer;color:red;text-align:right;"><i class="fa fa-close"></i>取消</a>
	<ul id="tree" class="ztree"></ul>
</div>
<div id="treediv2" style='overflow:scroll;display:none; position:absolute;width:300px;height:200px;background-color:#eeffdd; border:1px solid #BEC0BF;padding:5px;font-size:12px;'>
	<a onclick="hidetreediv2();" href="#" class="link-red mr5" style="cursor:pointer;color:red;text-align:right;"><i class="fa fa-close"></i>取消</a>
	<ul id="tree2" class="ztree"></ul>
</div> -->

<!-- 赋角色 -->
<div id="roleDiv" style="display:none;">
	 <div class="pt0" id="smIframe">
       <div class="right-form mt0">
       <form class="add-form" id="editForm" method="post" action="#" onsubmit="return false;">
          <input type="hidden" id="s_userId" value='' />
		<ul class="w100">
               
               <li style="width:100%;">
                   <label class="ser-label">选择角色：</label>
					
				<div class="area-div clearfix">
              <div class="pull-left" >
              
                  <dl class="area-list-left " id="area-list-left" style="height:370px">
                      <dt>已选择</dt>
                      <dd><input type="text" class="w100 mt5" id="area-left-search" placeholder="搜索"/></dd>
                  </dl>
              </div>

              <div class="btn-group pull-left">
                <div class="btn-middle">
                  <button class="go-right" onclick="addArea()"> &gt; </button>
                  <button class="go-left" onclick="delArea()"> &lt; </button>
                </div>
              </div>
              <div class="pull-left" >
                  
                 <dl class="area-list-right" id="area-list-right" style="height:370px">
                  <dt>未选择</dt>
                  <dd><input type="text" class="w100 mt5" id="area-right-search" placeholder="搜索"/></dd>
              </dl>
          </div>
          </div>	
               </li>             
                  
               <li class="w-per">
                   
                   <div class="form-content clearfix" style="padding-left:175px">
                   		<input   type="hidden" id="currentId"/>
                       <button class="btn btn-orange" id="savebtn_grantRoles" onclick="grantRoles()" ><i class="fa fa-save"></i> 保 存 </button>
                       <button id="cancelBtn" class="btn btn-default" onclick="layer.close(indx);"><i class="fa fa-reply"></i> 返 回 </button>
                   </div>
               </li>
            </ul>
    	</form>
    </div>
  </div>        
	      
</div>


	 <script src="${ctx}/static/js/search-more.js"></script>  <!--更多查询条件--> 
	<script src="${ctx}/static/js/jquery.ztree.all-3.5.js"></script>
<script type="text/javascript">


currentPageNo = parseInt('${pageBean.currentPage}');
currentPageSize = parseInt('${pageBean.pageSize }');
totalPageCount = parseInt('${pageBean.totalPage}');
queryUrl = '${ctx}/user/list';

$(document).ready(function(){
	 loadConent('${queryList }/table','',true);
});

function clearCondition(){
	$("#s_unitId").val("");
	clearForm('#_query_form');
}

function closeLayerOpen(){
	layer.close(indx);
}

function goUpdateUser(_url, _title) {
	 var ids = getListTableCheckboxValue() ;
	 if( ids == '' || ids.split(",").length>1){
		 warnTip('请选择一条记录');
		 return;
	 }
	layer.open({
		type : 2,
		title : _title,
		maxmin : false,
		shadeClose : false, //点击遮罩关闭层
		area : [ '850px', '500px' ],
		content : _url + "&userId=" + ids
	});
}

//启用
function enable(){
	//检查是否选中已经是启用状态的用户
	/* var isUserOn = false;
	$("#_list_table tr td input[name='checkboxOne']:checked").each(function(index,element){
		if(1 == $(element).attr("userStatus")){
			isUserOn = true;
			return;
		}
	});
	if(isUserOn){
		warnTip('请选择停用用户');
		return;
	} */
	
	deleteById('请确认是否启用',1);
}
//停用
function ban(){
	
	deleteById('请确认是否停用',0);
}

//启用或停用
function deleteById(msg,status) {
	
	var ids = getListTableCheckboxValue() ;
	 if( ids == ''){
		 warnTip('请选择一条记录');
		 return;
	 }
	 layer.confirm(msg, {
	 	    btn: ['确定', '取消']
	 	    ,yes: function(index){
	 	    	$.post("${ctx}/user/deleteByIds",{'ids':ids,'status':status},function(result){
	 	  		if(result.code=="success"){
	 	  			 successTip();
	 	  			//刷新列表
	 	  			jumpPage();
	 	  		}else{
	 	  		errorTip();
	 	  		}
	 	  	},"json");
	 	    }
	 	});
		
		

	}

	//layer层的index
	var indx;
	//保存角色数据
	var roleList = [];
	
	//用户赋予角色
	function goUserRoles() {
		
		 var ids = getListTableCheckboxValue() ;
		 if( ids == '' || ids.split(",").length>1){
			 warnTip('请选择一条记录');
			 return;
		 }
		
		var id = ids;
		var allRoles;
		var userRoles;
		$("#currentId").val(id);
		//保存角色数据，重新定义，抛弃旧数据
		roleList = [];
		//清除左边旧数据
		showlist('area-list-left',roleList, 0);
		//清除右边旧数据
		showlist('area-list-right',roleList, 1);
		//清空搜索框
		$("#area-left-search").val('');
		$("#area-right-search").val('');
		
	 	 $.post("${ctx}/user/getRoses",{userId:id},function(result){
			userRoles = result.left;
			allRoles = result.right;
			
			if (userRoles != null) {
                $(userRoles).each(function () {
                	roleList.push({"area":this.name,"id":this.id,"num":0});
                
                });
            }
			if (allRoles != null) {
                $(allRoles).each(function () {
                	roleList.push({"area":this.name,"id":this.id,"num":1});
                
                });
            }
			
			//显示左边的新数据
			showlist('area-list-left',roleList, 0);
            //显示右边的新数据
			showlist('area-list-right',roleList, 1);
			 
            //显示div
			indx = layer.open({
		       	  type: 1,
		       	  shade: false,
		       	  title: "赋角色", 
		       	  content: $('#roleDiv'), //捕获的元素
		       	  area: ['850px', '500px'] ,
		       	  cancel: function(index){
		       	  layer.close(index); 
		       	  //this.content.show();
		       	  } 
		       	});
         }, "json");  
		
	}

	//更新用户的角色
	function grantRoles(){
		$(".savebtn_grantRoles").attr('disabled','disabled');
		var userId = $("#currentId").val();
		var roleIds = '';
	
		var index = 0;
		for(var i in roleList){
			
			if(0 == roleList[i].num){
				if(index == 0){
					roleIds = roleList[i].id;
					
					index++;
				}else {
					roleIds = roleIds + ',' + roleList[i].id;
				}
			}
			
		}
		console.log("保存用户选择的角色roleIds= " +roleIds);
		$.post("${ctx}/user/saveUserRoses", {userId:userId,roleIds:roleIds}, function(result) {
			if (result.code == "success") {
				successTip();
				layer.close(indx);
				$("#savebtn_grantRoles").removeAttr('disabled');
			} else {
				errorTip();
				$("#savebtn_grantRoles").removeAttr('disabled');
			}
		}, "json");
		
	}
//选项框相关
//显示列表，testList表示显示全部数据，
    function showlist(id,list,num){
        $('#'+id).find('dd[id*=dd]').remove();
        var newNode = '';
        for(var i in list){
            if (list[i].num == num) {
                newNode+='<dd id="dd_'+i + '">' + list[i].area + '</dd>';
            };
        }
        $("#"+id).append(newNode)
    }

    //自动完成查找
    function autoComplete(id,list,num){
        var meetlist=[];//满足查找条件保存在数组中
        if(old_value!==''){
            if(num == 0){
                //查找条件，并赋值
                for(var i in list){
                    if(list[i].area.indexOf(old_value)>=0&&list[i].num!=1){
                        meetlist.push(list[i]);
                    }
                }
                //显示满足查找条件的列表
                showlist(id,meetlist,num);
            }else{
                for(var i in list){
                    if(list[i].area.indexOf(old_value)>=0&&list[i].num!=0){
                        meetlist.push(list[i]);
                    }
                }
                //显示满足查找条件的列表
                showlist(id,meetlist,num);
            }
            
        }
        if(old_value==''){
            //输入框为空，显示全部列表
            if(num == 0){
                for(var i in list){
                    if(list[i].num != 1 && list[i].num != 0){
                        list[i].num = num;
                    }
                }
                showlist(id,roleList,num)
            }else{
                for(var i in list){
                    if(list[i].num!=0){
                        list[i].num = 1;
                    }
                }
                showlist(id,roleList,num)
            }
            
        }
        /* count+=1; */
    }



    //左边输入框查找显示
    document.getElementById("area-left-search").onkeyup = function(){
        old_value=$('#area-left-search').val();
        autoComplete("area-list-left",roleList,0);
    };
    //右边输入框查找显示
    document.getElementById("area-right-search").onkeyup = function(){
        old_value=$('#area-right-search').val();
        autoComplete("area-list-right",roleList,1);
    };


    $(".area-list-left").on("click","dd:not(:first)",function(){       //点击元素dd
        var cla = $(this).attr("class");
        if (cla) {
            //以空格为断点分割字符串
            var clarray = cla.split(" ");          
        }
        //判断active是否包含在数组里，不包含则返回-1
        var num = jQuery.inArray("active",clarray);   
        if ( num == -1) {
            $(this).addClass("active");
        }else{
            $(this).removeClass("active");
        }
    });

    $(".area-list-right").on("click","dd:not(:first)",function(){
        var cla = $(this).attr("class");
        if (cla) {
            var clarray = cla.split(" ");
        }
        var num = jQuery.inArray("active",clarray);
        if ( num == -1) {
            $(this).addClass("active");
        }else{
            $(this).removeClass("active");
        }
    });




function addArea(){
    $(".area-list-left .active").each(function(){
        var ddText = $(this).html();
        for(var i in roleList) {
            if (ddText == roleList[i].area) {
                roleList[i].num = 1;
            };
        }
    })
    $(".area-list-right dd:not(:first)").each(function(){
        var ddText = $(this).html();
        for(var i in roleList) {
            if (ddText == roleList[i].area) {
                roleList[i].num = 1;
            };
        }
    })
    showlist('area-list-left',roleList, 0);
    showlist('area-list-right',roleList, 1);
    document.getElementById("area-left-search").value = '';
    document.getElementById("area-right-search").value = '';
}
function delArea(){
    $(".area-list-right .active").each(function(){
        var ddText = $(this).html();
        for(var i in roleList) {
            if (ddText == roleList[i].area) {
                roleList[i].num = 0;
            };
        }
    });
    $(".area-list-left dd:not(:first)").each(function(){
        var ddText = $(this).html();
        for(var i in roleList) {
            if (ddText == roleList[i].area) {
                roleList[i].num = 0;
            };
        }
    });
    showlist('area-list-right',roleList, 1);
    showlist('area-list-left',roleList, 0);
    document.getElementById("area-right-search").value = '';
    document.getElementById("area-left-search").value = '';
}
//选项框 相关结束

	$(document).ready(function() {
		/* $("#s_postName").focus(function() {
            var divObj = $("#treediv");
        	var txtObj = $("#s_postName");
        	showDiv(divObj,txtObj,postsetting,"${ctx}/user/getPost");
		}); */
		$("#s_unitName").focus(function() {
			var divObj = $("#treediv2");
        	var txtObj = $("#s_unitName");
        	showDiv2(divObj,txtObj,unitsetting2,"${ctx}/user/getUnit");
        	
		});
		
	});
</script>